function UserPanel() {
};

// 静态
UserPanel.instance = UserPanel;

UserPanel.faceUrl = "userController";

/**
 * 用户表
 */
UserPanel.userDatagrid = null;

/**
 * 编辑用户窗口
 */
UserPanel.userEditWindow = null;

/**
 * 用户授权窗口
 */
UserPanel.authorizedWin = null;

/**
 * 功能树
 */
UserPanel.funTreegrid = null;

/**
 * 用户角色表
 */
UserPanel.roleDatagrid = null;

/**
 * 分页条
 */
UserPanel.userPager = null;

/**
 * 初始化并加载数据
 */
UserPanel.init = function(){
	UserPanel.loadToolbar();
	UserPanel.userDatagrid = mini.get("userDatagrid");
	UserPanel.userEditWindow = mini.get("userEditWindow");
	UserPanel.userPager = mini.get("userPager");
	UserPanel.authorizedWin = mini.get("roleEditWindow");
	UserPanel.roleDatagrid = mini.get("roleDatagrid");
	UserPanel.funTreegrid = mini.get("funTreegrid");
	UserPanel.renderer();
	UserPanel.reload();
};

/**
 * 加载按钮
 */
UserPanel.loadToolbar = function() {
	var array = new Array("system_user_add", "system_user_edit", "system_user_del",
			"system_user_author", "system_user_refresh");
	var array2 = MiniuiTools.isHasPurview(array);
	for ( var i = 0; i < array2.length; i++) {
		mini.get(array[i]).setVisible(array2[i]);
	}
};

/**
 * 加载全部用户
 * @param pageIndex  页码
 * @param pageSize  每页多少条
 */
UserPanel.loadUser = function(pageIndex, pageSize){
	$.ajax( {
		type: 'POST',
		dataType: 'json',
		url: __root+"/"+UserPanel.faceUrl,
		cache: false,
		data: {
			method: "find",
			size: pageSize,
			pageNo: pageIndex
		},
		success: function(json) {
			if (json) {
				UserPanel.userPager.setTotalCount(json.rowCount);
				UserPanel.userDatagrid.loadData(json.resultList);
				return;
			}
			return;
		},
		error: function(obj, ertxt) { /* 失败回调函数.这里是网络失败, 比如500错误等 */
			//mini.hideMessageBox(messageId);
			mini.alert("初始化数据错误：" + ertxt);
		}
	});
};

/**
 * 首先加载所有角色列表，然后选中select用户具有的角色列表
 * @return
 */
UserPanel.loadRoles = function(userId) {
	RolePanel.query( {
		pageNo: 0,
		size: 9999
	}, function(data){
		
		UserPanel.roleDatagrid.loadData(data.resultList);
		
		/* 加载用户所具有的角色列表 */
		$.ajax( {
			type: 'POST',
			dataType: 'json',
			url: __root+"/"+UserPanel.faceUrl,
			data: {
				userId: userId,
				method: 'getUserRoleRelation'
			},
			success: function(json) {
				if (json) {
					for ( var i = 0; i < json.length; i++) {
						var data = UserPanel.roleDatagrid.data;
						for ( var j = 0; j < data.length; j++) {
							if(json[i].roleId == data[j].roleId){
								UserPanel.roleDatagrid.setSelected(data[j]);
							}
						}
					}
				}
				return;
			},
			error: function(e, errtxt) {
				mini.alert("系统错误：" + errtxt);
				return;
			}
		});
		
	});
};

/**
 * 首先加载所有功能列表，然后选中select用户具有的功能列表
 * @return
 */
UserPanel.loadFunTree = function(userId) {
	var fns = [];
	for ( var i = 0; i < parent.ClientData.allFunNodeData.length; i++) {
		fns.push(parent.ClientData.allFunNodeData[i]);
	}
	UserPanel.funTreegrid.loadData(fns);
	
	var param = {
			method: 'getUserFunNodeRelation',
			userId: userId
		};

		$.ajax( {
			type: 'POST',
			dataType: 'json',
			url: __root+"/"+UserPanel.faceUrl,
			data: param,
			success: function(json) {
				var nodes = [];
				for ( var i = 0; i < json.length; i++) {
					var funNode = MiniuiTools.findTreeNode(json[i].funId, fns, null, "funId",99);
					nodes.push(funNode);
				}
				UserPanel.funTreegrid.uncheckAllNodes();
				UserPanel.funTreegrid.collapseAll(); 
				UserPanel.funTreegrid.checkNodes(nodes);
				return;
			},
			error: function(e, errtxt) {
				mini.alert("系统错误：" + errtxt);
				return;
			}
		});
	};
	
/**
 * 新增用户按钮事件
 */
UserPanel.add = function(){
	var form = new mini.Form("#userEditform");
	form.clear();
	UserPanel.userEditWindow.show();
};

/**
 * 编辑用户按钮事件
 */
UserPanel.edit = function(){
	if (!MiniuiTools.hasPurview("system_user_edit")) {
		mini.showMessageBox({title:"提示",message:"糟糕，您没有权限访问！",iconCls:"mini-messagebox-info",buttons: ["ok"]});
		return;
	}
	
	var rowData = UserPanel.userDatagrid.getSelected();
	
	var form = new mini.Form("#userEditform");
	form.clear();
	if(rowData){
		rowData.issys = rowData.issys ? true : false;
		form.setData(rowData);
		UserPanel.userEditWindow.show();
	}else{
		mini.alert("请选中要修改的用户");
	}
};

/**
 *  删除用户信息，考虑到用户暂时不多且防止误删，所以执行单项删除
 *  可根据实际情况修改是否需要多项删除
 */
UserPanel.del = function() {
	if (!MiniuiTools.hasPurview("system_user_del")) {
		mini.showMessageBox({title:"提示",message:"糟糕，您没有权限访问！",iconCls:"mini-messagebox-info",buttons: ["ok"]});
		return;
	}
	
	var rowData = UserPanel.userDatagrid.getSelected();
	
	if(!rowData){
		mini.alert("请选中要删除的记录！");
	}else{
		
		if(rowData.issys){
			mini.showMessageBox({title:"提示",message:"对不起，该用户不能删除！",iconCls:"mini-messagebox-info",buttons: ["ok"]});
			return;
		}
		
		mini.confirm("确定要删除登录名为  " + "<span style='color: red;'> " +rowData.uname + "</span>" + "  的用户吗？", "删除用户",
	            function (action) {            
	                if (action == "ok") {
	                		var ids = [];
	                		ids.push(rowData.userId);

	                		$.ajax( {
	                			type: 'POST',
	                			dataType: 'json',
	                			url: __root+"/"+UserPanel.faceUrl,
	                			cache: false,
	                			data: {
	                				method: 'delete',
	                				"userId": ids,
	                				lslUser: gbOperateUser,
				    				lslAddress: gbOperateIp
	                			},
	                			success: function(json) {
	                				if (json.errorCode == 0) {
	                					UserPanel.reload();
	                				}
	                				return;
	                			},
	                			error: function(obj, ertxt) { /* 失败回调函数.这里是网络失败, 比如500错误等 */
	                				alert("初始化数据错误：" + ertxt);
	                			}
	                		});
	                } 
	            }
	        );
	}
};

/**
 * 用户授权按钮
 */
UserPanel.authorized = function(){
	if (!MiniuiTools.hasPurview("system_user_author")) {
		mini.showMessageBox({title:"提示",message:"糟糕，您没有权限访问！",iconCls:"mini-messagebox-info",buttons: ["ok"]});
		return;
	}
	
	var rowData = UserPanel.userDatagrid.getSelected();
	
	if(rowData){
		//加载表格的数据
		UserPanel.loadRoles(rowData.userId);
		
		//加载树的数据
		UserPanel.loadFunTree(rowData.userId);
		UserPanel.authorizedWin.show();
		
	}else{
		mini.alert("请选中要授权的用户");
	}
};

/**
 * 隐藏用户信息弹出窗口
 */
UserPanel.closeUserButton = function(){
	UserPanel.userEditWindow.hide();
};

/**
 * 隐藏授权信息弹出窗口
 */
UserPanel.closeAuButton = function(){
	UserPanel.authorizedWin.hide();
};

/**
 * 加载数据
 */
UserPanel.reload = function(){
	UserPanel.loadUser(UserPanel.userPager.pageIndex, UserPanel.userPager.pageSize);
};

/**
 * 对表格数据渲染
 */
UserPanel.renderer = function(){
	UserPanel.userDatagrid.on("drawcell", function (e){
		var  field = e.field, value = e.value;
		if(field == "uname"){e.cellHtml = "<a href='javascript:UserPanel.edit();'>[" + value + "]</a>";;}
		if(field == "glText"){e.cellHtml = "<a href='javascript:UserPanel.authorized();'>【授权】</a> <a href=\"javascript:UserPanel.del();\">【删除】</a>";};
	});
};


/**
 * 页码改变事件
 */
UserPanel.pagechanged = function(e){
      UserPanel.loadUser(e.pageIndex, e.pageSize);
};

/**
 * 保存或更新用户信息
 */
UserPanel.save = function(){
	var form = new mini.Form("#userEditform");
	
	form.validate();
    if (form.isValid() == false) return;
	
	var data = form.getData();
	data.method = "save";
	data.issys = (data.issys == "true") ? '1' : '';
	data.lslUser = gbOperateUser;
	data.lslAddress = gbOperateIp;
	
	$.ajax( {
		type: 'POST',
		dataType: 'json',
		url: __root+"/"+UserPanel.faceUrl,
		cache: false,
		data: data,
		success: function(json) {
			if (json.errorCode == 0) {
				UserPanel.reload();
				UserPanel.userEditWindow.hide();
			}
			return;
		},
		error: function(obj, ertxt) { /* 失败回调函数.这里是网络失败, 比如500错误等 */
			mini.alert("初始化数据错误：" + ertxt);
		}
	});
};

/**
 * 保存授权信息
 * @return
 */
UserPanel.savePurview = function() {
	var messageid = mini.loading("保存中，请稍等 ...", "loadding");
	
	/* 基本信息提取 */
	var param = {
		method: 'setPurview',
		userId: '',
		Uname: '',
		funId: [],
		funName: [],
		roleId: []
	};
	param.userId = UserPanel.userDatagrid.getSelected().userId;
	param.Uname =UserPanel.userDatagrid.getSelected().uname;

	/* 功能节点信息提取 */
	var funs = UserPanel.funTreegrid.getCheckedNodes();
	for ( var i = 0, l = funs.length; i < l; i++) {
		param.funId.add(funs[i].funId);
		param.funName.add(funs[i].name);
	}

	/* 角色信息提取 */
	var roles = UserPanel.roleDatagrid.getSelecteds();
	for ( var j = 0; j < roles.length; j++) {
		param.roleId.push(roles[j].roleId);
	}
	
	param.lslUser = gbOperateUser;
	param.lslAddress = gbOperateIp;

	$.ajax( {
		type: 'POST',
		dataType: 'json',
		cache: false,
		url: __root+"/"+UserPanel.faceUrl,
		data: param,
		success: function(text) {
			UserPanel.closeAuButton();
			mini.hideMessageBox(messageid);
			return;
		},
		error: function(e, errtxt) {
			mini.alert("系统错误：" + errtxt + e);
			UserPanel.closeAuButton();
			mini.hideMessageBox(messageid);
			return;
		}
	});
};
